<!--  当发现页面出现缓存问题时 可以将页面的 keep-alive 标签注释掉  主要在侧边栏和主页内容    -->

<template>
  <div class="c-app theContainer-vue">
    <!--滚动提示-->
    <div class="rollingClass" v-show="warnList">
      <div class="rollingTitle">
        <h5>告警信息：</h5>
        <Icon type="md-close" @click="warnList = !warnList" />
      </div>

      <div style="max-height: 500px; overflow-y: auto">
        <template v-for="item in showSocketMessage">
          <div class="rollingbody">
            <div class="rollingbodytitle">
              <div>节点：{{ item.nodeName }}</div>
              <div>{{ item.messageTime }}</div>
            </div>
            <div>告警信息：{{ item.messageContent }}</div>
          </div>
        </template>
      </div>
    </div>

    <!--    v-show="tip&&socketMessage.length"-->
    <!--提示-->
    <div
      class="tipClass"
      :style="tipMove"
      v-show="tip && socketMessage.length"
      @dragstart="dragstart1($event)"
      @drag="dragStart($event)"
      @dragend="dragEnd($event)"
      @click.stop="showWarnList"
    >
      <Icon type="ios-close" class="tipClose" @click.stop="tip = !tip" />
      <Badge
        :count="socketMessage.length ? socketMessage.length : 0"
        :show-zero="true"
      >
        <Icon type="md-bulb" />
      </Badge>
    </div>

    <!-- 解决chrome浏览器input页面刷新会自动填充用户名问题-->
    <input type="password" style="display: none; width: 0; height: 0" />
    <!--写法2 -->
    <!--   <keep-alive :include="$store.state.includeRoute" :exclude="$store.state.excludeRoute" >-->
    <TheSidebar
      ref="sidebar"
      @toParent="fromChild"
      :mag="mag"
      item-clicked="itemClicked"
      :showData.sync="showDat"
      v-show="
        path !== '/dataOptimization' &&
        path !== '/adminHome' &&
        path !== '/taskManage/BuildEmergencyTask' &&
        path !== '/emergencyMonitor' &&
        path !== '/detailTaskRegularRisk'
      "
    ></TheSidebar>

    <div
      v-if="path == '/taskManage/BuildEmergencyTask'"
      class="c-wrapperss"
      :style="{
        'margin-left':
          path == '/taskManage/BuildEmergencyTask' ? '0' : mrlevalue,
      }"
    >
      <!-- 头部导航 -->
      <TheHeader ref="headerContainer" @searchinput="searchinput" :mag="mag" />
      <!-- 左侧导航 -->
      <div class="body">
        <!-- 页面主体 -->
        <div class="c-body">
          <main class="c-main" :style="{ height: 'calc(100vh - 60px)' }">
            <CContainer>
              <transition name="fade">
                <router-view></router-view>
              </transition>
            </CContainer>
          </main>
        </div>
      </div>
    </div>
    <div
      v-else
      class="c-wrapper"
      :style="{
        'margin-left':
          path == '/dataOptimization' ||
          path == '/adminHome' ||
          path == '/emergencyMonitor' ||
          path  == '/detailTaskRegularRisk' ||
          !showDat
            ? '0'
            : mrlevalue,
      }"
    >
      <!-- 头部导航 -->
      <TheHeader ref="headerContainer" @searchinput="searchinput" :mag="mag" />
      <!-- 左侧导航 -->
      <div class="body">
        <!-- 页面主体 -->
        <div class="c-body bodyStyle">
          <!--左上右下的三角-->
          <div class="leftTopTriangle" v-show="path !== '/adminHome'">
            <div class="boxSizeTop"></div>
          </div>
          <div class="rightBottomTriangle" v-show="path !== '/adminHome'">
            <div class="boxSizeBottom"></div>
          </div>
          <!-- :style="{height: 'calc(100vh - 60px)'}" -->
          <main class="c-main" :style="{ height: 'calc(100vh - 60px)' }">
            <CContainer>
              <router-view
                v-if="
                  showRouterView &&
                  (firstRoutePath === 'processing' ||
                    firstRoutePath === 'qualityCheck')
                "
              ></router-view>
              <!--   <transition name="fade"  firstRoutePath>-->
              <keep-alive :include="keepAlivePage" v-else>
                <router-view v-if="showRouterView"></router-view>
              </keep-alive>
              <!--</transition>-->
            </CContainer>
          </main>
        </div>
      </div>
      <!-- 页面底部公司信息 -->
      <!-- <TheFooter class="Bfooter" /> -->
    </div>

    <!--刷新单页-->
    <div class="refreshOutBox">
      <div class="refreshInBox" style="" @click="reFreshData">
        <i class="fa fa-refresh"></i>
      </div>
    </div>
    <!-- <div class="buttonhide" v-show="!showDat && (path !== '/adminHome'|| path !== '/dataOptimization')"> -->
    <div
      class="buttonhide"
      v-show="
        !showDat &&
        path !== '/adminHome' &&
        path !== '/dataOptimization' &&
        path !== '/emergencyMonitor' &&
        path  == '/detailTaskRegularRisk'
      "
    >
      <Icon type="md-arrow-dropright" @click="hideSideBar" />
    </div>
  </div>
</template>


<script>
import TheSidebar from "./TheSidebar";
import TheHeader from "./TheHeader";
import TheFooter from "./TheFooter";

import rolling from "../template/rolling/rolling";
import SockJS from "sockjs-client";
import Stomp from "stompjs";

import store from "../stores/stores";
export default {
  name: "TheContainer",
  components: { TheSidebar, TheHeader, TheFooter, rolling },
  data() {
    return {
      firstRoutePath: "",
      userName: "",
      keepAlivePage: [
        "qualityCheck",
        "allTask",
        "taskChildren",
        "taskToExecute",
        "taskExecute",
        "taskEnd",
        "algoManage",
        "dataQueryModel",
        "qcProductionLineModel",
        "userManage",
        "menuManage",
        "organization",
        "dictManage",
        "taskTypeManage",
      ],
      showRouterView: true,
      opeanresult: [],
      titleresult: [],
      mag: "",
      mrlevalue: "200px", //默认左侧树宽度
      datamodel: [],
      newList: [],
      select: "processmodel",
      timer: "",
      nav: [
        {
          _name: "CSidebarNav",
          _children: [],
        },
      ], //控制左侧栏树结构数据
      showDat: "responsive",

      stompClient: null,
      socketMessage: [],
      showSocketMessage: [],
      tip: false,
      warnList: false,
      tipMove: { bottom: "100px", rigth: "15px" },
    };
  },
  computed: {
    //当前路由
    path() {
      return this.$route.path;
    },
  },
  mounted() {
    let that = this;
    this.userName = window.sessionStorage.getItem("user");
    window.onresize = () => {
      clearTimeout(that.timer);
      that.timer = setTimeout(() => {
        that.$store.state.screenWidth = document.documentElement.clientWidth; //窗口宽度
        that.$store.state.screenHeight = document.documentElement.clientHeight; //窗口高度
      }, 100);
    };

    this.getCatalog(this.$route.path);
    this.getTaskCatalog(this.$route.path);
    // this.getTreeList(2);
    // this.getModelCategoryTree();

    //抛出方法用于外部调用,刷新左侧机构数
    this.$bus.$on("getTaskCatalog", (data) => {
      this.getTaskCatalog(this.$route.path);
    });
    //抛出方法用于外部调用,刷新左侧机构数
    this.$bus.$on("getCatalog", (data) => {
      this.getCatalog(this.$route.path);
    });

    this.connectSocketJs();
  },
  methods: {
    dragstart1() {
      console.log("dragstart1");
    },
    dragStart($event) {
      console.log("dragStart");
      //this.tipMove={left:$event.clientX+"px",top:$event.clientY+"px"}
      this.tipMove.left = $event.clientX + "px";
      this.tipMove.top = $event.clientY + "px";
    },
    dragEnd($event) {
      console.log("dragEnd");
      //  this.tipMove={left:$event.clientX+"px",top:$event.clientY+"px"}
      this.tipMove.left = $event.clientX + "px";
      this.tipMove.top = $event.clientY + "px";
    },

    showWarnList() {
      if (!this.socketMessage.length) return;
      this.warnList = true;
      let data = [];
      this.showSocketMessage = JSON.parse(JSON.stringify(this.socketMessage));
      this.socketMessage = [];
      this.showSocketMessage.forEach((item) => {
        data.unshift(item.id.toString());
      });
      this.http
        .put(this.$api.homeLoginOthers.updateDeliveryWebStatusByIds, data)
        .then((res) => {});
    },
    connectSocketJs() {
      let that = this;
      var USER = this.$store.state.user.userId;
      var ROLE = this.$store.state.user.roleInfo[0].id;
      // 设置连接的U
      var URL = this.$api.homeLoginOthers.webSocketWarn;
      // 设置 WebSocket 进入端点
      // websocket存在session
      var URL_ALL_PATH = URL + "?token=" + ROLE + "__" + USER;
      // 设置订阅消息的请求地址
      var SUBSCRIBE = "/user/queue/sendUserOrRole";
      // 设置 SOCKET
      var socket = new SockJS(URL_ALL_PATH);
      // 配置 STOMP 客户端
      this.stompClient = Stomp.over(socket);
      // STOMP 客户端连接
      this.stompClient.connect({}, function (frame) {
        /* 订阅信息 */
        that.stompClient.subscribe(SUBSCRIBE, function (responseBody) {
          that.tip = true;
          that.socketMessage = that.socketMessage.concat(
            JSON.parse(responseBody.body)
          );
        });
      });
    },

    // 任务监控跳转过来刷新左侧树, 对应头部不同的模块
    getCatalog(path) {
      let self = this;
      let url = this.$api.homeLoginOthers.getMyCatalog + "?t=skdh";
      let param = {
        systemId: systemId,
        type: 0,
        treeType: 3,
      };
      if (path.indexOf("processing") != -1) {
        self.getTreeList(2);
      } else if (path.indexOf("qualityCheck") != -1) {
        self.getTreeList(1);
      } else if (path.startsWith("/taskManage")) {
        self.getTaskCatalog(path);
      } else {
        this.http
          .get(url, param)
          .then((res) => {
            if (res.data.success) {
              let catalogData = res.data.data;
              if (self.userName !== "pieadmin") {
                for (let i = 0; i < catalogData.length; i++) {
                  if (catalogData[i]._children) {
                    self.getNewCatalog(catalogData[i]._children);
                  }
                }
              }
              for (let i = 0; i < catalogData.length; i++) {
                let item = catalogData[i]._children;
                if (path.includes(catalogData[i].to)) {
                  if (item == undefined) {
                    item = [];
                  }
                  for (let q = 0; q < item.length; q++) {
                    if (item[q]._children == undefined) {
                      continue;
                    } else {
                      // 遍历数组，添加icon
                      self.getChildrenDataAddIcon(item[q]._children);
                    }
                  }
                  self.refresh(item);
                }
              }
            } else {
              this.$Message.error(res.data.message);
            }
          })
          .catch((err) => {});
      }
    },
    //处理特殊节点不显示问题
    getNewCatalog(data) {
      let settingName = "/manage/authManage/menuManage"; //配置管理
      let dicName = "/manage/dictManage"; //字典项管理
      for (let i = 0; i < data.length; i++) {
        if (data[i].to === settingName || data[i].to === dicName) {
          data.splice(i, 1);
          i--;
          break;
        } else {
          let children = data[i]._children;
          if (children) {
            this.getNewCatalog(children);
          }
        }
      }
    },

    // 此路由下/taskManage执行  任务中心左侧树 调用refresh方法
    getTaskCatalog(path) {
      if (path.startsWith("/taskManage")) {
        let path = this.$api.homeLoginOthers.queryTaskCatalog;
        let param = {
          userName: window.sessionStorage.getItem("user"),
        };
        this.http.get(path, param).then((res) => {
          if (res.data.code == 0) {
            let dataList = res.data.data;
            for (let i = 0; i < dataList.length; i++) {
              let element = dataList[i];
              if (element._children == undefined || element._children == null)
                continue;
              if (element._children.length > 1) {
                element._name = "CSidebarNavDropdown";
              }
            }
            this.refresh(dataList);
          }
        });
      }
    },

    // 此路由下/qualityCheck和 /processing下执行  任务中心左侧树 调用setTreeNodeRoute和refreshcolor两个方法
    //刷新进入search    getTreeList
    getTreeList(groupId) {
      let _this = this;
      let path = this.$api.homeLoginOthers.workFlowGroup;
      let params = {
        groupId: groupId,
        systemId: systemId,
      };
      //处理一级和二级的地址
      let urlPreSuffix = "/processing/common/"; //处理加工 默认
      if (groupId == 1) {
        //1、质检 2 处理加工
        urlPreSuffix = "/qualityCheck/common/";
      }
      this.http
        .get(path, params)
        .then((res) => {
          if (res.data.code == 0) {
            let list = res.data.data;
            for (var i = 0; i < list.length; i++) {
              let tempData = list[i];
              //下载页面跳转进来给 我的文件 添加背景
              if (
                tempData.url === "/processing/myFile" &&
                _this.$route.params.type === "downLoadFile"
              ) {
                _this.$set(tempData, "color", "class");
              }

              tempData.icon = "cil-settings";
              //处理一级
              _this.setTreeNodeRoute(list[i], urlPreSuffix);
              //处理二级
              let children = tempData.children;
              if (!children) continue;

              for (let j = 0; j < children.length; j++) {
                _this.setTreeNodeRoute(children[j], urlPreSuffix);
                //处理三级
                let children1 = children[j].children;
                if (children1.length < 1) continue;
                for (let m = 0; m < children1.length; m++) {
                  _this.setTreeNodeRoute(children1[m], urlPreSuffix);
                }
                children[j]._children = children1;
              }
              tempData._children = children;
            }
            _this.refreshcolor(list, groupId);
          } else {
            _this.$Message.error(res.data.message);
          }
        })
        .catch((err) => {
          if (
            err.data.code === 401 &&
            err.data.message ===
              "Cluster Node count is more than authorize count"
          ) {
            that.$Message.error("授权已过期，请重新申请授权!");
          } else {
            that.$Message.error(err.data.message);
          }
        });
    },

    //函数的作用是修改树结构名称,路由连接地址,和渲染的标签
    setTreeNodeRoute(node, urlPreSuffix) {
      node.name = node.title;
      if (node.children == undefined || node.children == null) {
        if (node.customLabel.toLowerCase() === "push") {
          node.to = node.url;
        }
        return;
      }
      if (node.children.length == 0) {
        node._name = "CSidebarNavItem";
        if (node.customLabel.toLowerCase() === "push") {
          //推送任务特殊处理
          node.to = node.url;
        } else {
          node.to = urlPreSuffix + node.customLabel + "/" + node.id;
        }
      } else {
        node._name = "CSidebarNavDropdown";
        let children = node.children;
        // for (let j = 0; j < children.length; j++) {
        //   this.setTreeNodeRoute(children[j], urlPreSuffix);
        // }
        // return node;
      }
    },

    //刷新左侧组织机构树的方法,并对左侧中的方法进行操作,数据赋值,并调用子组件方法
    refreshcolor(data, groupId) {
      if (this.$refs.sidebar) {
        if (data.length == 0) {
          // 左侧树显隐
          this.$refs.sidebar.show = false;
        } else {
          this.$refs.sidebar.show = "responsive";
        }
        this.$refs.sidebar.nav[0]._children = data;
        this.$refs.sidebar.sidebarcolor();
        this.$refs.sidebar.searchinputdel();
      }
      this.nav[0]._children = data;
      /* this.$refs.sidebar.nav[0]._children = [];*/
    },

    /*
     * 以下工具函数
     * */
    //刷新左侧组织机构树的方法,并对左侧中的方法进行操作,数据赋值
    refresh(data) {
      if (this.$refs.sidebar) {
        if (data.length == 0) {
          // 左侧树显隐
          this.$refs.sidebar.show = false;
        } else {
          this.$refs.sidebar.show = "responsive";
        }
        this.$refs.sidebar.nav[0]._children = data;
        this.$refs.sidebar.clearOtherClassName();
      }
      this.nav[0]._children = data;
      //通过这一步向TheSidebar传递左侧树结构,
      /*  this.$refs.sidebar.nav[0]._children = [];*/
    },
    // 循环数组添加icon  添加值cil-arrow-thick-right
    getChildrenDataAddIcon(data) {
      for (let i = 0; i < data.length; i++) {
        data[i].icon = "cil-arrow-thick-right";
      }
    },
    // 调用TheHeader组件中的showMonitor方法
    headershowMonitor() {
      this.$refs.headerContainer.showMonitor();
    },
    // 调用TheHeader组件中的showTask方法
    headershowTask() {
      this.$refs.headerContainer.showTask();
    },
    // 调用TheHeader组件中的showOrder方法
    headershowOrder() {
      this.$refs.headerContainer.showOrder();
    },
    // TheHeader向父组件传mag值
    searchinput(data) {
      this.mag = data;
    },
    //左侧树向父组件抛出宽度值
    fromChild(msg) {
      this.mrlevalue = msg;
    },
    //其他页面调用用于刷新左侧树结构数据
    getTreeListByGroupId(groupId) {
      this.opeanresult = [];
      this.titleresult = [];
      // 树节点刷新
      if (groupId == 1) {
        this.getTreeList(1);
      } else if (groupId == 2) {
        this.getTreeList(2);
      }
    },
    getModelCategoryTree() {
      let self = this;
      let path = this.$api.homeLoginOthers.processmodel;
      this.http.get(path).then((res) => {
        let temp = res.data.data.length;
        if (res.data.success) {
          for (let i = 0; i < temp.length; i++) {
            let temps = {};
            (temps._name = "CSidebarNavBrand"),
              (temps.name = temp[i].name),
              (temps.to = "/model/common/model"),
              self.datamodel.push(temps);
          }
          //   self.treeData = res.data.data;
          //   self.modelCateId = self.treeData[0].id;
          //   self.name = self.treeData[0].title;
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    // 刷新页面  单页刷新有点问题需要重新设计
    reFreshData() {
      let that = this;
      let keepAliveArr = JSON.parse(JSON.stringify(this.keepAlivePage));
      let courentRoute = this.$route.name;
      let courentRouteIndex = keepAliveArr.findIndex((item) => {
        return item === courentRoute;
      });
      this.keepAlivePage = this.keepAlivePage.filter((item) => {
        return item !== courentRoute;
      });
      that.showRouterView = false;
      this.$nextTick(function () {
        if (courentRouteIndex !== -1) {
          that.keepAlivePage.push(courentRoute);
        }
        that.showRouterView = true;
      });
    },
    hideSideBar() {
      this.showDat = "responsive";
    },
  },
  watch: {
    //浏览器前进或后退时，刷新左侧树
    $route(to, from) {
      //判断路由缓存
      if (to.name != "login") {
        /*刷新左侧树结构*/

        let toUrlName = to.path.split("/")[1];
        this.firstRoutePath = toUrlName;
        let fromUrlName = from.path.split("/")[1];
        if (toUrlName !== fromUrlName && to.name !== "adminHome") {
          //在其中写入判断路由跳转
          this.$bus.$emit("getCatalog");
        }
      }
    },
    path(newVal, oldVal) {},
  },
  beforeDestroy() {
    this.stompClient.disconnect(function () {});
    this.$bus.$emit("loginOut");
  },
};
</script>

<style scoped>
/* 主体添加滚动条。当页面过长显示不全显示  start*/
/* 滚动条宽高 */
::-webkit-scrollbar {
  /* width: 10px;
  height: 2px; */
}
/* 滚动条颜色 */
::-webkit-scrollbar-thumb {
  background-color: rgb(168, 168, 168);
}
/* 滚动条插槽颜色 */
::-webkit-scrollbar-track-piece {
  background-color: rgb(211, 210, 210);
}
::-webkit-scrollbar-thumb:vertical {
  -webkit-border-radius: 5px;
}
::-webkit-scrollbar-thumb:horizontal {
  -webkit-border-radius: 5px;
}
/* ::-webkit-scrollbar-track-piece{ 
  background-color:#f8f8f8; 
} */
/* end */
.c-main {
  padding-top: 0;
}
.container {
  /* overflow: hidden; */
  position: relative;
  max-width: unset;
  padding: 10px;
  box-sizing: border-box;
  height: 100%;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
.c-header {
  /* background: url(../assets/icons/nav.png); */
  height: 60px;
  border: none;
  /*  border-bottom: 6px solid #000;*/
}
.body {
  display: flex;
}
.leftNav {
  position: absolute;
  top: 50px;
}
.Bfooter {
  position: fixed;
  bottom: 0;
  left: 0;
}
.c-sidebar-nav-link {
  white-space: pre-line;
  overflow: scroll;
}
@media screen and (max-width: 991px) {
  /* .pstyle {
    font-size:0.8rem;
  } */
  .c-wrapper {
    margin-left: 20px !important;
  }
}

.bodyStyle {
  position: relative;
}

.leftTopTriangle {
  position: absolute;
  left: 0;
  top: 0;
  width: 0;
  height: 0;
  border-top: 120px solid var(--label-font-color, #5d8bc4);
  border-right: 120px solid transparent;
}
.rightBottomTriangle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 0;
  height: 0;
  border-bottom: 120px solid var(--three-color, #cbe5f5);
  border-left: 120px solid transparent;
}
.boxSizeTop {
  width: 120px;
  height: 120px;
  background-color: #ebedef;
  position: absolute;
  top: -110px;
  left: 10px;
  border-radius: 5px;
}
.boxSizeBottom {
  width: 120px;
  height: 120px;
  background-color: #ebedef;
  position: absolute;
  bottom: -110px;
  right: 10px;
  border-radius: 5px;
}
.refreshOutBox {
  width: 26px;
  height: 26px;
  padding: 2px;
  box-sizing: border-box;
  position: fixed;
  right: 4px;
  top: 30px;
  z-index: 1000003;
}

.refreshInBox {
  width: 100%;
  height: 100%;
  background-color: var(--label-font-color, #5d8bc4);
  border-radius: 3px;
  text-align: center;
  color: white;
}

.buttonhide {
  position: absolute;
  top: calc(50% - 60px);
  left: -10px;
  font-size: 26px;
  color: #0d86ff;
  z-index: 1000;
}
</style>


<style scoped lang="scss">
.rollingClass {
  position: absolute;
  top: 60px;
  left: 50%;
  z-index: 10000000;
  padding: 10px;
  width: 600px;
  margin-left: -200px;
  overflow-y: auto;
  background-color: rgba(252, 161, 48, 0.7);
  color: #ffffff;
}

.rollingTitle {
  display: flex;
  justify-content: space-between;
  height: 30px;
  align-items: center;
  border-bottom: 1px solid #ffffff;
}
.rollingbody {
  margin: 10px;
  padding: 10px;
  background-color: rgba(235, 84, 81, 0.4);
}
.rollingbodytitle {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.tipClass {
  position: fixed;
  bottom: 50px;
  right: 15px;
  color: rgb(252, 161, 48);
  z-index: 100000;
  font-size: 60px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 83px;
  height: 80px;
}

.tipClose {
  font-size: 34px;
  color: #0a0a0a;
  position: absolute;
  right: 11px;
  top: -4px;
  z-index: 11111;
  display: none;
}

.tipClass:hover {
  .tipClose {
    display: block;
  }
}
/deep/.ivu-badge-count {
  top: 37px;
  right: 53px;
  background-color: rgb(252, 161, 48);
}

@keyframes roatyus {
  0% {
    box-shadow: 0 0 5px 5px rgba(235, 84, 81, 0.8);
  }
  100% {
    box-shadow: 0 0 5px 5px rgba(235, 84, 81, 0);
  }
}
.warning {
  animation-name: roatyus;
  animation-duration: 2s;
  animation-iteration-count: infinite;

  animation-direction: alternate;
}

@keyframes rotatey {
  0% {
    color: rgb(255, 153, 0);
  }
  50% {
    color: rgb(128, 134, 149);
  }
  100% {
    color: rgb(237, 64, 20);
  }
}
.warnTip {
  animation-name: rotatey;
  animation-duration: 5s;
  animation-iteration-count: infinite;

  animation-direction: alternate;
}
</style>
